package com.yyk.yiliao.ui.find.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import com.google.android.material.appbar.AppBarLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseFragment;
import com.yyk.yiliao.adapter.CommonTabPagerAdapter;
import com.yyk.yiliao.adapter.WenjiankangAdapter;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.bean.Wenjiankang_Info;
import com.yyk.yiliao.ui.find.activity.FindSearch_Activity;
import com.yyk.yiliao.ui.gongyong.activity.WebViewActivity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.widget.diver.more.SpacesItemDecoration;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.HomeArticletitle_Info;
import com.yyk.yiliao.bean.HomeArticletype_Info;
import com.yyk.yiliao.bean.HomeDoctordata_Info;
import com.yyk.yiliao.widget.CustomViewPager;
import com.yyk.yiliao.widget.ViewPagerScroller;
import com.yyk.yiliao.widget.indicator.PointIndicator;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.HttpException;
import retrofit2.Retrofit;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by ${ZKbilian} on 2018/7/18 0018.
 * 发现--Fragment
 */

public class Find_Fragment extends BaseFragment {

    @BindView(R.id.nFind_jkjt)
    RecyclerView nFindJkjt;
    @BindView(R.id.nFind_mytj)
    RecyclerView nFindMytj;


    @BindView(R.id.tabLayout)
    XTabLayout tabLayout;
    @BindView(R.id.nFind_fvp)
    ViewPager nFindFvp;
    @BindView(R.id.nFind_tabbtn)
    ImageView nFindTabbtn;
    @BindView(R.id.nHome_scroll)
    NestedScrollView nHomeScroll;
    @BindView(R.id.nHome_app)
    AppBarLayout nHomeApp;
    @BindView(R.id.nFind_tab)
    NestedScrollView nFindTab;

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title2)
    TextView tvTitle2;
    @BindView(R.id.tv_title3)
    TextView tvTitle3;
    @BindView(R.id.nHome_search)
    TextView nHomeSearch;
    @BindView(R.id.iv_wjk22)
    ImageView ivWjk22;
    @BindView(R.id.vp_wjk)
    CustomViewPager vpWjk;
    @BindView(R.id.ll_wjk)
    LinearLayout llWjk;
    @BindView(R.id.iv_wjk)
    ImageView ivWjk;
    @BindView(R.id.pointindicator)
    PointIndicator pointindicator;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;

    private final Retrofit retrofit2 = RxUtils.getInstance().retrofit;
    private BaseRecyclerAdapter<HomeDoctordata_Info.DataBean> homeDoctordataAdapter;
    private WenjiankangAdapter wenJiankangAdapter;

    private BaseRecyclerAdapter<Wenjiankang_Info> jkjtAdapter;

    List<HomeArticletitle_Info.DataBean> HomeArticletitleList = new ArrayList<>();
    List<HomeArticletype_Info.DataBean> HomeArticletypeList = new ArrayList<>();
    List<HomeDoctordata_Info.DataBean> HomeDoctordataList = new ArrayList<>();
    List<Wenjiankang_Info> jkjtList = new ArrayList<>();


    @Override
    public int getLayoutId() {
        return R.layout.fragment_find;
    }

    @Override
    public void initView() {
        initRefresh();
    }

    private void initRefresh() {
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initPost();
                        //禁止点击内容
                        smartrefreshlayout.setDisableContentWhenRefresh(true);
                        smartrefreshlayout.finishRefresh();
                    }
                }, 1500);

            }
        });
    }

    @Override
    public void initData() {
        //因为适配器中有一个不是网络请求方式，所以必须在initPos前面
        initAdapter();
        initPost();

    }

    private void initAdapter() {
        homeDoctordataAdapter = new BaseRecyclerAdapter<HomeDoctordata_Info.DataBean>(getActivity(), HomeDoctordataList, R.layout.adapter_item_find_mytj) {
            @Override
            public void convert(BaseRecyclerHolder holder, HomeDoctordata_Info.DataBean item, int position, boolean isScrolling) {
                holder.setText(R.id.tv_true_name, item.getTrue_name());
                if (!TextUtils.isEmpty(item.getTitle())) {
                    holder.setText(R.id.tv_title, item.getTitle());
                }
                holder.setImageByUrl(R.id.iv_picture, ApiService.BASE_URL + item.getPicture());
                int grade = item.getGrade();
                if (grade == 1) {
                    holder.setText(R.id.tv_grade, "住院医师");
                } else if (grade == 2) {
                    holder.setText(R.id.tv_grade, "主治医师");
                } else if (grade == 3) {
                    holder.setText(R.id.tv_grade, "副主任医师");
                } else {
                    holder.setText(R.id.tv_grade, "主任医师");
                }

            }
        };
        nFindMytj.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        nFindMytj.setAdapter(homeDoctordataAdapter);
        homeDoctordataAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("toolbar_tv", HomeDoctordataList.get(position).getTrue_name());
                int did = HomeDoctordataList.get(position).getDid();
                intent.putExtra("url", ApiService.H5_URL + "views/Hospital/DoctorsInfo.html?from=app&did=" + did + "&Sources=3");
                startActivity(intent);
            }
        });
        //健康讲堂
        jkjtAdapter = new BaseRecyclerAdapter<Wenjiankang_Info>(getActivity(), jkjtList, R.layout.adapter_item_find_jkjt) {
            @Override
            public void convert(BaseRecyclerHolder holder, Wenjiankang_Info item, int position, boolean isScrolling) {
                if (position == 0) {
                    holder.getView(R.id.iv_zjsp).setVisibility(View.VISIBLE);
                }
                holder.setText(R.id.tv_title, item.getTitle());
                holder.setText(R.id.tv_name, item.getName());
                holder.setImageResource(R.id.iv_img, item.getImg());
            }
        };
        nFindJkjt.setLayoutManager(new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false));
        //添加ItemDecoration，item之间的间隔
        int leftRight = dip2px(4);
        int topBottom = dip2px(10);
        nFindJkjt.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));//
        nFindJkjt.setAdapter(jkjtAdapter);
        jkjtAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {


            }
        });
    }

    private void initPost() {
        setMoreHuodong(true);
        setTabXinWen(true);
        setMytj(true);
        setJiankangjiangtai(true);
        setWenjiankang();
    }

    /**
     * 名医推荐
     */
    private void setMytj(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
map.put("sign", Md5Util2.createSign(map));
        retrofit2.create(ApiService.class).postHomeDoctordata(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<HomeDoctordata_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                        onComplete();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(HomeDoctordata_Info info) {
                        Logger.i("名医推荐:" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                HomeDoctordataList.clear();
                            }
                            if (info.getData().size() > 0 && info.getData() != null) {
                                HomeDoctordataList.addAll(info.getData());
                            }
                            homeDoctordataAdapter.notifyDataSetChanged();

                        }
                    }

                });
    }

    /**
     * 设置底部新闻
     */
    private void setTabXinWen(final boolean flag) {
        Map<String, String> map = new TreeMap<>();

        map.put("sign", Md5Util2.createSign(map));
        retrofit2.create(ApiService.class).postHomeArticletype(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<HomeArticletype_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                        onComplete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        //失败的时候调用-----一下可以忽略 直接 callBack.onFaild("请求失败");
                        onFailure(" 请求失败");

                    }

                    @Override
                    public void onNext(HomeArticletype_Info info) {
                        if (info.getCode() == 1) {
                            if (flag) {
                                HomeArticletypeList.clear();
                            }
                            if (info.getData().size() > 0 && info.getData() != null) {
                                HomeArticletypeList.addAll(info.getData());
                            }
                            List<String> string = new ArrayList<>();
                            final List<String> integers = new ArrayList<>();
                            string.add("推荐");
                            integers.add("0");
                            for (int i = 0; i < HomeArticletypeList.size(); i++) {
                                string.add(HomeArticletypeList.get(i).getName());
                                integers.add(String.valueOf(HomeArticletypeList.get(i).getId()));
                            }

                            CommonTabPagerAdapter adapter = new CommonTabPagerAdapter(getChildFragmentManager()
                                    , string.size(), string, getActivity());
                            adapter.setListener(new CommonTabPagerAdapter.TabPagerListener() {
                                @Override
                                public Fragment getFragment(int position) {
                                    Find_TabFragment fragment = Find_TabFragment.newInstance(position);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("Find_TabFragment", integers.get(position) + "");
                                    fragment.setArguments(bundle);

                                    return fragment;
                                }
                            });
                            nFindFvp.setAdapter(adapter);
                            tabLayout.setupWithViewPager(nFindFvp);
                            nFindFvp.setCurrentItem(0);
                        }
                    }
                });
    }

    /**
     * 更多活动
     *
     * @param flag
     */
    private void setMoreHuodong(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
map.put("sign", Md5Util2.createSign(map));
        retrofit2.create(ApiService.class).postHomeArticletitle(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<HomeArticletitle_Info>() {
                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                        onComplete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        //失败的时候调用-----一下可以忽略 直接 callBack.onFaild("请求失败");
                        if (e instanceof HttpException) {
                            HttpException httpException = (HttpException) e;
                            //httpException.response().errorBody().string()
                            int code = httpException.code();
                            if (code == 500 || code == 404) {
                                onFailure("服务器出错");
                            }
                        } else if (e instanceof ConnectException) {
                            onFailure("网络断开,请打开网络!");
                        } else if (e instanceof SocketTimeoutException) {
                            onFailure("网络连接超时!!");
                        } else {
                            onFailure("发生未知错误" + e.getMessage());
//                            Logger.e("MyFind", e.getMessage());
                        }
                    }

                    @Override
                    public void onNext(HomeArticletitle_Info info) {
                        Logger.i("更多活动:" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                HomeArticletitleList.clear();
                            }
                            if (info.getData() != null && info.getData().size() > 0) {
                                HomeArticletitleList.addAll(info.getData());
                            }
//                            Logger.e("看看刷新后集合变大了没" + HomeArticletitleList.size());
                            String title = HomeArticletitleList.get(0).getTitle();
                            String title2 = HomeArticletitleList.get(1).getTitle();
                            String title3 = HomeArticletitleList.get(2).getTitle();
                            tvTitle.setText(title);
                            tvTitle2.setText(title2);
                            tvTitle3.setText(title3);
                        }
                    }
                });

    }

    /**
     * 健康讲堂
     */

    private void setJiankangjiangtai(boolean flag) {
        List<Wenjiankang_Info> list = new ArrayList<>();
        int[] img = {R.mipmap.img_fxjt1, R.mipmap.img_fxjt2, R.mipmap.img_fxjt3, R.mipmap.img_fxjt4};
        String[] title = {"懂得养生的人早起不会喝这四种水", "体内上火别轻易服药，选择对的很重要", "天天早饭喝豆浆，其实很很多人喝错了", "每天坚持用山楂泡水，身体为什么还出症状？"};
        String[] name = {"刘丽敏", "陈亚楠", "邓钡亿", "郑文"};
        for (int i = 0; i < title.length; i++) {
            Wenjiankang_Info wenjiankang_info = new Wenjiankang_Info();
            wenjiankang_info.setImg(img[i]);
            wenjiankang_info.setName(name[i]);
            wenjiankang_info.setTitle(title[i]);
            list.add(wenjiankang_info);
        }
        if (flag) {
            jkjtList.clear();
        }
        Logger.e("健康讲堂"+jkjtList.size());
        if (list.size() > 0 && list != null) {
            jkjtList.addAll(list);
        }
        Logger.e("健康讲堂2"+jkjtList.size());

        jkjtAdapter.notifyDataSetChanged();
    }

    private boolean isAuto = true; //滑动冲突解决
    private boolean isTouch = false;
    private Handler handler;
    private Timer timer;
    private TimerTask timerTask;

    //问健康
    private void setWenjiankang() {
        List<String> wjkList = new ArrayList<>();
        wjkList.add("为何用了这么多护肤品，还没有白里透红自然美？");
        wjkList.add("湿气不除，湿疹缠身，湿疹最佳治疗方法？");
        wjkList.add("总是口渴，五心烦热，是不是阴虚了？");
        wjkList.add("为什么会免疫力下降？");
        wjkList.add("您认为怎么从根本上解决以上医疗问题?适当降低药品价格,使药品价格符合大众水平");
        final List<View> vpList = new ArrayList<>();
        for (int i = 0; i < wjkList.size(); i++) {
            View view = View.inflate(getActivity(), R.layout.adapter_item_find_wjk, null);
            TextView viewById = view.findViewById(R.id.tv_title);
            viewById.setText(wjkList.get(i));
            vpList.add(view);
        }

        wenJiankangAdapter = new WenjiankangAdapter(vpList, getActivity());
        //优化滑动效果
        ViewPagerScroller scroller = new ViewPagerScroller(getActivity());
        scroller.initViewPagerScroll(vpWjk);
        vpWjk.setAdapter(wenJiankangAdapter);

        pointindicator.bindViewPager(vpWjk, new PointIndicator.PageScrollStateChangedListenter() {
            @Override
            public void onPageScrollStateChanged(int state) {
                //禁止触摸时候 自动轮播
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    isTouch = false;
                } else {
                    isTouch = true;
                }
            }
        });

    }

    /**
     * 开启问健康滑动轮播  自定义ViewPager轮播图指示器 - 简书  https://www.jianshu.com/p/60be684d897d
     */
    private void startLoop() {
        //如果是自动轮播时，让代表显示页面的指示位置+1;
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    //如果是自动轮播时，让代表显示页面的指示位置+1;
                    loop();
                }
            }
        };
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        };
        timer.schedule(timerTask, 300, 3000);
    }

    /**
     * 关闭轮播 ，不知道可行吗
     */
    private void stopLoop() {
        //停止handler
        handler.removeCallbacksAndMessages(null);
        handler = null;
        //关闭计时器
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }

    }

    private void loop() {
        //如果手动滑动时不处理
        if (isTouch) {
            return;
        }
        if (!isAuto) {
            return;
        }
        int curPos = vpWjk.getCurrentItem();
        curPos = (++curPos) % wenJiankangAdapter.getCount();
        vpWjk.setCurrentItem(curPos);
    }

    @Override
    public void onStart() {
        super.onStart();

        startLoop();
    }

    @Override
    public void onStop() {
        super.onStop();

        stopLoop();
    }


    public int dip2px(float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics());
    }

    private void onFailure(String msg) {
    }


    private void onComplete() {

    }

    private void onSuccess(Object info) {

    }

    @OnClick({R.id.toolbar, R.id.nFind_tabbtn, R.id.nHome_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar:
                break;
            case R.id.nFind_tabbtn:
                break;
            case R.id.nHome_search:
                Intent intent = new Intent(getContext(), FindSearch_Activity.class);
                startActivity(intent);
                break;
        }
    }

}
